import OSS from 'ali-oss'
import { v4 as UUID4 } from 'uuid';

const ossConfig = {
  // secure: true, // https
  region: "oss-cn-hangzhou", //根据你买的那个区的做相应的更改
  bucket: "tr-pen",
  accessKeyId: "LTAI5tNrcUDBScjUYpHoxHeU",
  accessKeySecret: "yP6qPDbXpkEmIlQnE2xKYcY2BXDcWf",
}
// 下载oss指定地址
export function downloadURL(url) {
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 上传oss
export function ossUpload(picForProject, fileBuffer) {
  let client = new OSS(ossConfig);

  const fileName = UUID4().toUpperCase().replace(/-/g, '')
  const suffix = fileBuffer.name.substr(fileBuffer.name.indexOf('.'))
  const url = `${picForProject}${fileName}${suffix}`

  async function put() {
    try {
      await client.put(url, fileBuffer)
      // await xxx(url) 在这里也可以直接把地址传给后端
      return { 'code': 200, 'url': url }
    } catch (e) {
      return e.message
    }
  }

  return put()
};

// 获取oss地址
export function showPrivateOss(picName) {
  let client = new OSS(ossConfig);

  async function getOssAddr() {
    try {
      let signUrl = client.signatureUrl(picName, { expires: 1800 }); // expires单位为秒
      return { 'code': 200, 'url': signUrl }
    } catch (e) {
      return e.message
    }
  }

  return getOssAddr()
};
// 显示oss地址(拿取oss里面的图片进行显示)
export function imgSig(baseURL) {
  const client = new OSS(ossConfig);
  // 生成带图片处理参数的文件签名URL，过期时间10分钟。
  let signUrl = client.signatureUrl(baseURL, { expires: 3600, 'process': 'image/resize,m_fixed,w_150,h_150/quality,q_100' });
  // console.log("signUrl=" + signUrl);
  return signUrl
  // console.log("signUrl=" + signUrl);
}


// 删除oss
export function deletePrivateOss(picName) {
//   let bucketName = '';
//   process.env.NODE_ENV === 'production' ? bucketName = '填你自己申请的' : bucketName = '填你自己申请的';
  let client = new OSS(ossConfig);

  async function deleteOssAddr() {
    try {
      return client.delete(picName);
    } catch (e) {
      return e.message
    }
  }

  return deleteOssAddr()
};
